package com.oocl.aeat.jms;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

import com.oocl.aeat.listener.JMSConsumerListener;
import com.oocl.aeat.service.VerifyService;
import com.oocl.aeat.service.factory.VerifyServiceFactory;
import com.oocl.aeat.util.ServerConfig;


/**
 * 消息消费者
 * @author Administrator
 *
 */
public class JMSConsumer {

	private static Connection connection;
	private static String rootPath;
	private static String queueName;
	
	/**
	 * 构造方法私有化
	 */
	private JMSConsumer(){}
	
	public static void setRootPath(String rootPath) {
		JMSConsumer.rootPath=rootPath;
	}
	
	public static void startServer() {
		init();
		service();
	}
	
	private static void init() {
		// 连接工厂
		ConnectionFactory connectionFactory; 
		try {
			connectionFactory=new ActiveMQConnectionFactory(ServerConfig.JMS_USERNAME,ServerConfig.JMS_PASSWORD,ServerConfig.JMS_TCP_CONNNECTION_URL);
			queueName=ServerConfig.JMS_CONSUMER_QUEUE;
			// 通过连接工厂获取连接
			connection=connectionFactory.createConnection();
			// 启动连接
			connection.start(); 
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
	private static void service() {
		try {
			Session session=connection.createSession(Boolean.FALSE, Session.CLIENT_ACKNOWLEDGE); 
			Destination destination=session.createQueue( queueName );  
			MessageConsumer messageConsumer=session.createConsumer(destination);
			
			VerifyService vs = VerifyServiceFactory.getInstance();
			JMSConsumerListener jmsConsumerListener=new JMSConsumerListener(vs,rootPath);
			messageConsumer.setMessageListener(jmsConsumerListener);
		} catch (JMSException e) {
			e.printStackTrace();
		} 
	}

	public static void stopServer() {
		destroy();
	}
	
	private static void destroy() {
		if(connection!=null){
			try {
				connection.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
	}

	
	
	
	
}
